<template>
  <div class="flex w-[100%]">
    <el-checkbox v-model="checked">{{ checkLabel }}</el-checkbox>
    <div class="text-[12px] text-[#e50113] ml-[4px]">
      {{ tips }}
    </div>
  </div>
  <div class="flex">
    <span>{{ label }}：</span>
  </div>
  <div class="w-[240px]">
    <NumberRange
      :suffix="suffix"
      :max="99999999999999"
      :value="rangeVal"
      @input="rangeVal = $event"
      checkValue
    />
  </div>
</template>

<script setup>
import NumberRange from '@/components/NumberRange/index.vue'

const props = defineProps({
  optionsData: { type: Object, default: () => ({}) },
  value: { type: Object, default: () => ({}) },
  label: { type: String, default: '' },
  tips: { type: String, default: '' },
  checkLabel: { type: String, default: '' },
  suffix: { type: String, default: 'RMB' },
})

const emit = defineEmits(['input'])

const checked = ref(false)
const rangeVal = ref({ min: undefined, max: undefined })

const handleReset = () => {
  checked.value = false
  rangeVal.value = { min: undefined, max: undefined }
}

watch(
  () => props.value,
  (val, newVal) => {
    const { min, max } = val || {}
    if (!Object.keys(val).length) {
      handleReset()
      return
    }
    if (JSON.stringify(val) === JSON.stringify(newVal)) return
    rangeVal.value = {
      min: min,
      max: max,
    }
    checked.value = min || max ? true : false
  },
  { deep: true, immediate: true }
)

watch(
  () => [rangeVal.value, checked.value],
  val => {
    const [_range, _checked] = val
    if (!_checked) {
      emit('input', { min: undefined, max: undefined })
      return
    }
    emit('input', { min: _range?.min, max: _range?.max })
  },
  { deep: true, immediate: true }
)
</script>
